package com.zou.lotterylucky.activity

import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.elvishew.xlog.XLog
import com.google.gson.Gson
import com.google.zxing.integration.android.IntentIntegrator
import com.jakewharton.rxbinding3.view.clicks
import com.kaopiz.kprogresshud.KProgressHUD
import com.v2.request.RequestCenter
import com.v2.utils.TToast
import com.v2.utils.okhttp.OkHttpRequestCallback
import com.zou.lotterylucky.R
import com.zou.lotterylucky.data.Order
import com.zou.lotterylucky.utils.*
import kotlinx.android.synthetic.main.activity_check.*
import org.greenrobot.eventbus.EventBus
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * 订单信息列表界面
 */
class OrderListActivity : BaseActivity() {
    private lateinit var adapter: DealsAdapter //适配器
    private var ordersData: MutableList<Order> = mutableListOf() //列表

    companion object {
        const val REQUEST_CODE_ORDER_DETAIL = 1
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_check)

        topbar.setTitle(R.string.order_info)
        topbar.addLeftBackImageButton().setOnClickListener { onBackPressed() }

        searchBtn.setOnClickListener {

            loadOrders()
        }

        scanBtn.setOnClickListener {
            IntentIntegrator(this)
                .setDesiredBarcodeFormats(IntentIntegrator.QR_CODE).initiateScan()
        }
        adapter = DealsAdapter(ordersData)
        rcv.layoutManager = LinearLayoutManager(this)
        rcv.adapter = adapter

        adapter.setOnItemClickListener { _, _, position ->
            val intent = Intent(this, OrderDetailActivity::class.java)
            intent.putExtra("from", 0)
            selectedOrder = adapter.data[position]
            startActivityForResult(intent, REQUEST_CODE_ORDER_DETAIL)
        }


        AidlUtil.instance.getTime("yyyy-MM-dd", object : TimeCallBack {
            override fun onError(msg: String?) {

            }

            override fun onSuccess(time: String?) {
                tv_time_start.text = time
                tv_time_end.text = time
            }
        })

        val dateFormatter = SimpleDateFormat("yyyy-MM-dd")
        var cal = Calendar.getInstance()
        val dateSetListener =
            DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
                cal.set(Calendar.YEAR, year)
                cal.set(Calendar.MONTH, monthOfYear)
                cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
                tv_time_start.text = dateFormatter.format(cal.time)
            }

        tv_time_start.clicks().throttleFirst(1000, TimeUnit.MILLISECONDS)
            .subscribe {
                DatePickerDialog(
                    this, dateSetListener,
                    cal.get(Calendar.YEAR),
                    cal.get(Calendar.MONTH),
                    cal.get(Calendar.DAY_OF_MONTH)
                ).show()
            }

        val dateSetListener1 =
            DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
                cal.set(Calendar.YEAR, year)
                cal.set(Calendar.MONTH, monthOfYear)
                cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
                tv_time_end.text = dateFormatter.format(cal.time)
            }

        tv_time_end.clicks().throttleFirst(1000, TimeUnit.MILLISECONDS)
            .subscribe {
                DatePickerDialog(
                    this, dateSetListener1,
                    cal.get(Calendar.YEAR),
                    cal.get(Calendar.MONTH),
                    cal.get(Calendar.DAY_OF_MONTH)
                ).show()
            }
    }

    override fun onResume() {
        loadOrders()
        super.onResume()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)

        if (requestCode == REQUEST_CODE_ORDER_DETAIL && resultCode == RESULT_OK) {
            finish()
        }

        if (result != null) {
            val str = result.contents
            XLog.e(str)
            try {
                val jsonBean = JSONObject(str)
                val number = jsonBean.getString("or")
                val machineNumber = SPUtils[this, "username", "0001"] as String
                val jihao = number.substring(0, machineNumber.length)
                if (jihao != machineNumber) {
                    ToastUtil.showMsg(this, "机号不符")
                    return
                }
                loadOrderByNumber(number)
//                selectedOrder = allOrders.find { it -> it.serialNumber == number }!!
//                if (selectedOrder != null) {
//                    val intent = Intent(this, OrderDetailActivity::class.java)
//                    intent.putExtra("from", 1)
//                    startActivity(intent)
//                } else {
//                    ToastUtil.showTipsNotFound(this)
//                }
            } catch (e: Exception) {
                XLog.e(e)
                ToastUtil.showTipsError(this, getString(R.string.error_qr))
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }

    @SuppressLint("SimpleDateFormat")
    private fun loadOrders() {
        val startTimeStr = tv_time_start.text.toString() + " " + "00:00:00"
        val startTimeDate = DateUtil.localToUTC(startTimeStr)
        val endTimeStr = tv_time_end.text.toString() + " " + "23:59:59"
        val endTimeDate = DateUtil.localToUTC(endTimeStr)
        RequestCenter.appGetOrders(
            SPUtils[this, "username", ""] as String,
            orderNumberTxt.text.toString(),
            "0",
//            SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTimeDate),
            startTimeStr,
//            SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTimeDate),
            endTimeStr,
            object : OkHttpRequestCallback {
                override fun onSuccess(response: String?) {
                    TLog.net(javaClass.simpleName + ", getOrders(), success:" + Gson().toJson(response))
                    try {
                        val data = JSONObject(response).getJSONArray("data")

                        ordersData = mutableListOf()
                        for (i in 0 until data.length()) {
                            val order = Order(data.getJSONObject(i))
                            if (order.isDeleted == 0) {
                                val orderBets = mutableListOf<BetCountEntity>()
                                val betsData = data.getJSONObject(i).getJSONArray("bet_numbers")
                                for (j in 0 until betsData.length()) {
                                    val bet = BetCountEntity()
                                    val betData = betsData.getJSONObject(j)
                                    bet.num = betData.getString("bet_number").replace("P", "").trim().toInt()
                                    bet.money = betData.getDouble("bet_money")
                                    bet.pool = betData.getInt("is_pool") == 1
                                    bet.type = betData.getString("bet_number").replace("P", "").trim().length
                                    if (bet.type == 1) {
                                        bet.type = 2
                                    }

                                    bet.belongTo = data.getJSONObject(i).getString("belong_to")
                                    bet.isWinner = betData.getInt("is_winner")
                                    bet.rank = betData.getInt("rank")
                                    bet.prizes = betData.getDouble("prizes")
                                    orderBets.add(bet)
                                }
                                order.bets.addAll(orderBets)
                                ordersData.add(order)
                            }
                        }
                        ordersData.reverse()
                        adapter.replaceData(ordersData)
                    } catch (e: JSONException) {
                        TToast.show("getOrders json error:$e")
                    }
                }

                override fun onFailure(error: String?) {
                    TToast.show("getOrders failure:$error")
                }
            }
        )
    }

    private fun loadOrderByNumber(number: String) {
        TLog.v("loadOrderByNumber():$number")
//        val requestQueue = Volley.newRequestQueue(this)
//
//        val url = Constants.SERVER_URL + "getOrderBySerialNumber"
//        val params = JSONObject()
//        params.put("machine_number", SPUtils[this, "username", ""])
//        params.put("serial_number", number)

        val hud = KProgressHUD.create(this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
            .setCancellable(false)
            .setAnimationSpeed(2)
            .setDimAmount(0.5f)
            .show()

        RequestCenter.appGetOrders(SPUtils[this, "username", ""] as String, number, null, null, null, object : OkHttpRequestCallback {
            override fun onSuccess(result: String?) {
                try {
                    hud.dismiss()
                    if (JSONObject(result).getJSONArray("data").length() < 1) {
                        ToastUtil.showTipsNotFound(this@OrderListActivity)
                        return
                    }
                    val data = JSONObject(result).getJSONArray("data")[0] as JSONObject
                    val orderBets = mutableListOf<BetCountEntity>()
                    val betsData = data.getJSONArray("bet_numbers")
                    val order = Order(data)
                    for (j in 0 until betsData.length()) {
                        val bet = BetCountEntity()
                        val betData = betsData.getJSONObject(j)
                        bet.num =
                            betData.getString("bet_number").replace("P", "").trim().toInt()
                        bet.money = betData.getDouble("bet_money")
                        bet.pool = betData.getInt("is_pool") == 1
                        bet.type =
                            betData.getString("bet_number").replace("P", "").trim().length
                        bet.belongTo = data.getString("belong_to")
                        bet.isWinner = betData.getInt("is_winner")
                        bet.rank = betData.getInt("rank")
                        bet.prizes = betData.getDouble("prizes")
                        orderBets.add(bet)
                    }
                    order.bets.addAll(orderBets)
                    selectedOrder = order
                    if (selectedOrder != null) {
                        val intent = Intent(this@OrderListActivity, OrderDetailActivity::class.java)
                        intent.putExtra("from", 1)
                        startActivity(intent)
                    } else {
                        ToastUtil.showTipsNotFound(this@OrderListActivity)
                    }
                } catch (e: JSONException) {
                    hud.dismiss()
                    TLog.net("getOrders() failure:$e")
                }
            }

            override fun onFailure(error: String?) {
                hud.dismiss()
                TLog.net("getOrders failure:$error")
            }
        })
    }

    private fun queryData(str: String) {
        val find = if (str.isEmpty()) {
            ordersData
        } else {
            ordersData.filter { it ->
                it.serialNumber.contains(str)
            }
        }
        adapter.replaceData(find)
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }
}

class DealsAdapter(data: MutableList<Order>) :
    BaseQuickAdapter<Order, BaseViewHolder>(R.layout.item_deal, data) {
    override fun convert(helper: BaseViewHolder, item: Order) {
        helper.setText(R.id.textOrder, item.serialNumber)
            .setText(R.id.textTime, "${item.timeStrAuto} Wifi")
            .setText(
                R.id.textMoney,
                "${item.bets.size * item.getRegionCounts()}${mContext.getString(R.string.zhugong)}${
                    DecimalFormat("0.00").format(item.getTotal())
                }"
            )
            .setText(R.id.textBelong, item.belongTo)
            .setVisible(R.id.t5, item.isWinner == 1)
            .setVisible(R.id.textPrize, item.isWinner == 1)
            .setText(R.id.textPrize, DecimalFormat("0.00").format(item.winningAmount))
        if (item.isWinner == 1 && item.isPaid == 1) {
            helper.setBackgroundColor(R.id.rootLayout, Color.parseColor("#FFB6C1"))
        } else {
            helper.setBackgroundColor(R.id.rootLayout, Color.parseColor("#00000000"))
        }
    }
}